package com.hjw.smsapp.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;

import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.droid.smsobserverlibrary.SmsBean;
import com.droid.smsobserverlibrary.SmsObserver;
import com.droid.smsobserverlibrary.SmsResponseCallback;
import com.droid.smsobserverlibrary.VerificationCodeSmsFilter;
import com.hjw.smsapp.FloatWindow;
import com.hjw.smsapp.R;

import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class SmsObserverService extends Service {
    private SmsObserver smsObserver;
    //悬浮窗
    private FloatWindow floatWindow;
    private boolean isFloatWindowStart = false;
    public static boolean open = false;
    private String username = "", smsIp = "";

    private SmsResponseCallback callback = new SmsResponseCallback() {
        @Override
        public void onCallbackSms(SmsBean sms, String smsContent) {
            postSms(sms);
        }
    };


    private void postSms(final SmsBean bean) {
        username = getSharedPreferences("data", Context.MODE_PRIVATE).getString("username", "");
        smsIp = getSharedPreferences("data", Context.MODE_PRIVATE).getString("smsIp", "");
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(smsIp)) {
            return;
        }
        OkHttpClient client = new OkHttpClient();//创建OkHttpClient对象。
        FormBody.Builder formBody = new FormBody.Builder();//创建表单请求体
        formBody.add("username", username);
        formBody.add("message", bean.getContent());
        final Request request = new Request.Builder()//创建Request 对象。
                .url(smsIp)
                .post(formBody.build())//传递请求体
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println(e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) {
                if (response != null && response.isSuccessful()) {//回调的方法执行在子线程。
                    try {
                        JSONObject result = new JSONObject(response.body().string());
                        System.out.println(result.toString(2));
                        //{"code":10001,"data":null,"msg":false}
                        int code = result.optInt("code");
                        String msg = result.optString("msg");
                        if (code == 10000) {
                            //成功
                            floatWindow.setFloatText(msg);
                            return;
                        } else {
                            //失败
                            floatWindow.setFloatText(msg);
                            return;
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                floatWindow.setFloatText("fail");
            }
        });
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        smsObserver = new SmsObserver(this.getApplicationContext(), callback, new VerificationCodeSmsFilter(""));
        smsObserver.registerSMSObserver();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        open = true;
        String channelId = "channel_01";
        String name = "channel_name";
        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW);
            if (notificationManager != null) {
                notificationManager.createNotificationChannel(mChannel);
            }
            notification = new Notification.Builder(this)
                    .setChannelId(channelId)
                    .setContentTitle("运行中")
                    .setContentText("app service is running")
                    .setSmallIcon(R.mipmap.ic_launcher).build();
        } else {
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setContentTitle("运行中")
                    .setContentText("app service is running")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setOngoing(true)
                    .setChannelId(channelId);//无效
            notification = notificationBuilder.build();
        }
        startForeground(1, notification);
        if (!isFloatWindowStart) {
            floatWindow = new FloatWindow(this);
            floatWindow.showFloatWindow();
            isFloatWindowStart = true;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        open = false;
        System.exit(0);
    }
}
